package com.suishoupai.xmb.controller;

import com.alibaba.druid.support.logging.Log;
import com.alibaba.druid.support.logging.LogFactory;
import com.alibaba.fastjson.JSON;
import com.suishoupai.xmb.entity.*;
import com.suishoupai.xmb.exception.XmbException;
import com.suishoupai.xmb.service.*;
import com.suishoupai.xmb.utils.PageUtil;
import com.suishoupai.xmb.utils.SecurityUserUtil;
import com.suishoupai.xmb.utils.ValidateUtil;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by caojian on 2017/4/10.
 */
@Controller
@RequestMapping("/wx")
public class UserWxController {
    private static final Log LOG = LogFactory.getLog(UserWxController.class);

    @Autowired
    private XiaoquService xiaoquService;
    @Autowired
    private UserSaleService userSaleService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private UserWxService userWxService;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private EvaluateService evaluateService;
    @Autowired
    private SearchService searchService;
    @Autowired
    private DeliveryDiscountService deliveryDiscountService;
    @Autowired
    private BaiduMapService baiduMapService;


    @PostMapping("/login")
    @PreAuthorize("permitAll()")
    @ResponseBody
    public Object login(HttpServletRequest request, String name, String headUrl, String code) {
        ValidateUtil.notNull(code);

        UserWx userWx = new UserWx();
        userWx.setOpenId(userWxService.code2openId(code));

        UserBuy userBuy = new UserBuy();
        userBuy.setName(name);
        userBuy.setHeadUrl(headUrl);

        String sessionId = request.getSession().getId();
        try {
            userWxService.login(userWx, userBuy, sessionId);
        } catch (XmbException e) {
            return AjaxMessage.newErrorHintMsg(e.getError());
        }

        //微信小程序特殊性，需将sessionId返回。
        return AjaxMessage.newSuccessMsg(sessionId);
    }

    @PostMapping("/logout")
    @PreAuthorize("hasRole('ROLE_USER')")
    @ResponseBody
    public Object logout(HttpServletRequest request) {
        request.getSession().invalidate();
        return AjaxMessage.newSuccessMsg();
    }

    @GetMapping("/sale")
    @PreAuthorize("hasRole('ROLE_USER')")
    @ResponseBody
    public Object getSaleList(long xiaoquId) {
        return AjaxMessage.newSuccessMsg(userSaleService.getSaleListByXiaoquId(xiaoquId));
    }

    /**
     * @param saleId
     * @return
     */
    @GetMapping("/sale/{saleId}")
    @PreAuthorize("hasRole('ROLE_USER')")
    @ResponseBody
    public Object saleDetails(@PathVariable("saleId") long saleId) {
        Map map = new HashMap();
        map.put("goodsList", goodsService.getEnableGoodsBySaleId(saleId));
        map.put("sale", userSaleService.getCutUserSaleByUserId(saleId));
        map.put("deliveryDiscounts", deliveryDiscountService.getListBySaleId(saleId));
        return AjaxMessage.newSuccessMsg(map);
    }

    /**
     * 获取订单列表
     *
     * @return
     */
    @GetMapping("/order")
    @PreAuthorize("hasRole('ROLE_USER')")
    @ResponseBody
    public Object orderList(@RequestParam Map map) {
        PageUtil.startPage(map, false);
        long userId = SecurityUserUtil.getUser().getId();
        Integer status = MapUtils.getInteger(map, "status", null);
        Long ordersId = MapUtils.getLong(map, "ordersId", null);//分页
        ValidateUtil.in(status, null, OrderStatusEnum.WAIT_PAY.getValue(), OrderStatusEnum.WAIT_SEND.getValue(), OrderStatusEnum.COMPLETE.getValue());
        List<CutOrders> cutOrdersList = ordersService.getOrdersListByUserIdAndStatus(userId, status, ordersId);
        return AjaxMessage.newSuccessMsg(cutOrdersList);
    }

    /**
     * 提交订单(未确认)
     *
     * @return
     */
    @PostMapping("/order")
    @PreAuthorize("hasRole('ROLE_USER')")
    @ResponseBody
    public Object orderCreate(String goodsList) {
        long userId = SecurityUserUtil.getUser().getId();
        ordersService.deleteNoConfirmOrder(userId);
        ValidateUtil.notNull(goodsList);
        List<GoodsSnapshot> goodsSnapshots = JSON.parseArray(goodsList, GoodsSnapshot.class);
        CutOrders cutOrders = null;
        try {
            cutOrders = ordersService.orderCreate(goodsSnapshots, userId);
        } catch (XmbException e) {
            return AjaxMessage.newErrorHintMsg(e.getError());
        }
        return AjaxMessage.newSuccessMsg(cutOrders);
    }

    /**
     * 确认订单
     *
     * @return
     */
    @PostMapping("/order/{orderId}")
    @PreAuthorize("hasRole('ROLE_USER')")
    @ResponseBody
    public Object orderConfirm(@PathVariable("orderId") long orderId, @RequestParam Map maps) {
        Long xiaoquId = MapUtils.getLong(maps, "xiaoquId", null);
        String contact = MapUtils.getString(maps, "contact", null);
        String address = MapUtils.getString(maps, "address", null);
        int type = MapUtils.getInteger(maps, "type", null);
        String note = MapUtils.getString(maps, "address", null);
        ValidateUtil.notNull(xiaoquId);
        ValidateUtil.notNull(contact);
        ValidateUtil.notNull(address);
        ValidateUtil.in(type, OrderTypeEnum.PAY_ON_DELIVERY.getValue(), OrderTypeEnum.ONLINE_PAYMENT.getValue());
        long userId = SecurityUserUtil.getUser().getId();
        try {
            Orders orders = new Orders();
            orders.setId(orderId);
            orders.setContact(contact);
            orders.setAddress(address);
            orders.setUserId(userId);
            orders.setType(type);
            orders.setNote(note);
            ordersService.orderConfirm(orders, xiaoquId);
        } catch (XmbException e) {
            if (e.isRepeatRequest()) {
                return AjaxMessage.newSuccessMsg();
            }
            return AjaxMessage.newErrorHintMsg(e.getError());
        }
        return AjaxMessage.newSuccessMsg();
    }

    /**
     * 关闭未支付订单
     *
     * @return
     */
    @PostMapping("/order/{orderId}/close")
    @PreAuthorize("hasRole('ROLE_USER')")
    @ResponseBody
    public Object closeNoPayOrder(@PathVariable("orderId") long orderId, @RequestParam Map map) {
        String description = MapUtils.getString(map, "description");
        ValidateUtil.notNull(description);
        description = "用户关闭订单：" + description;
        long userId = SecurityUserUtil.getUser().getId();
        try {
            ordersService.closeNoPayOrder(orderId, description, userId);
        } catch (XmbException e) {
            if (e.isRepeatRequest()) {
                return AjaxMessage.newSuccessMsg();
            }
            return AjaxMessage.newErrorHintMsg(e.getError());
        }
        return AjaxMessage.newSuccessMsg();
    }

    /**
     * 店铺评价列表
     *
     * @param map
     * @return
     */
    @GetMapping("/evaluate")
    @PreAuthorize("hasRole('ROLE_USER')")
    @ResponseBody
    public Object evaluateList(@RequestParam Map map) {
        Long saleId = MapUtils.getLong(map, "saleId", null);
        Long evaluateId = MapUtils.getLong(map, "evaluateId", null);
        ValidateUtil.notNull(saleId);
        List<CutEvaluate> cutEvaluates = evaluateService.getEvaluateListBySaleId(saleId, evaluateId);
        return AjaxMessage.newSuccessMsg(cutEvaluates);
    }

    /**
     * 评价
     *
     * @param evaluate
     * @return
     */
    @PostMapping("/evaluate")
    @PreAuthorize("hasRole('ROLE_USER')")
    @ResponseBody
    public Object evaluateAdd(Evaluate evaluate) {
        ValidateUtil.notNull(evaluate.getOrdersId());
        ValidateUtil.notNull(evaluate.getScore());
        ValidateUtil.isNull(evaluate.getReply());
        evaluate.setUserId(SecurityUserUtil.getUser().getId());
        try {
            evaluateService.add(evaluate);
        } catch (XmbException e) {
            if (e.isRepeatRequest()) {
                return AjaxMessage.newSuccessHintMsg("你已经评过分了。");
            }
            return AjaxMessage.newErrorHintMsg(e.getError());
        }
        return AjaxMessage.newSuccessMsg();
    }

    /**
     * 搜索商品和店铺
     *
     * @param map
     * @return
     */
    @GetMapping("/search")
    @PreAuthorize("hasRole('ROLE_USER')")
    @ResponseBody
    public Object index(@RequestParam Map map) {
        PageUtil.startPage(map, false);
        String name = MapUtils.getString(map, "name");
        Long xiaoquId = MapUtils.getLong(map, "xiaoquId", null);
        ValidateUtil.notNull(xiaoquId);
        List<CutSearch> cutSearches = searchService.searchGoodsAndSale(name, xiaoquId);
        return AjaxMessage.newSuccessMsg(cutSearches);
    }

    /**
     * 搜索小区
     *
     * @param map
     * @return
     */
    @GetMapping("/search/xiaoqu")
    @PreAuthorize("hasRole('ROLE_USER')")
    @ResponseBody
    public Object xiaoqu(@RequestParam Map map) {
        PageUtil.startPage(map, false);
        String name = MapUtils.getString(map, "name", null);
        List<CutSearch> cutSearches = searchService.searchXiaoqu(name);
        return AjaxMessage.newSuccessMsg(cutSearches);
    }

    /**
     * 定位
     *
     * @return
     */
    @GetMapping("/location")
    @PreAuthorize("permitAll()")
    @ResponseBody
    public Object location(Location location) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("xiaoquList", xiaoquService.filterLocation(location));
        map.put("addressName", baiduMapService.getAddressName(location.getLatitude(), location.getLongitude()));
        return AjaxMessage.newSuccessMsg(map);
    }
}
